package com.longrise.co.ui.carlife.fragment;

import android.Manifest;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.longrise.co.R;
import com.longrise.co.api.ApiConstants;
import com.longrise.co.api.CommonPara;
import com.longrise.co.ui.carlife.adapter.NewsAdapter;
import com.longrise.co.ui.carlife.contract.CarLifeContract;
import com.longrise.co.ui.carlife.model.CarLifeModel;
import com.longrise.co.ui.carlife.model.NewsBean;
import com.longrise.co.ui.carlife.presenter.CarLifePresenter;
import com.longrise.co.ui.carlife.webview.WebViewActivity;
import com.longrise.co.ui.kckp.TrafficMapActivity;
import com.longrise.co.ui.login.fragment.LoginFragment;
import com.longrise.co.utils.Constants;
import com.ly.common.base.BaseFragment;
import com.ly.common.baserx.RxBus;
import com.ly.common.commonutils.StringUtils;

import butterknife.Bind;
import rx.functions.Action1;

import static com.longrise.co.R.id.recyclerView;

/**
 * Created by luoyang on 2017-6-26.
 */

public class CarLifeFragment extends BaseFragment<CarLifePresenter, CarLifeModel> implements CarLifeContract.CarLifeView<NewsBean>, SwipeRefreshLayout.OnRefreshListener, View.OnClickListener, BaseQuickAdapter.OnRecyclerViewItemClickListener {

    @Bind(R.id.head_back)
    RelativeLayout mHeadBack;
    @Bind(R.id.head_title)
    TextView mHeadTitle;
    @Bind(R.id.right_btn)
    ImageView mRightBtn;
    @Bind(recyclerView)
    RecyclerView mRecyclerView;
    @Bind(R.id.refresh_layout)
    SwipeRefreshLayout mRefreshLayout;

    private View mHeadView;

    private RelativeLayout mIllegalInquiriesRl;
    private RelativeLayout mAnnouncementRl;
    private RelativeLayout mChargingStationRl;
    private RelativeLayout mTrafficNavigationRl;
    private RelativeLayout mKckpRl;

    private RelativeLayout noDataTip;

    private TextView mCarLifeMore;

    private NewsAdapter mAdapter;


    private int mPageCount = 0;
    private int mPageNum = 1;

    public static final int MY_PERMISSION_REQUEST_CODE = 124;

    private boolean isFirstLoad = true;

    private static final String[] PERMISSIONS_CONTACT = new String[]{Manifest.permission.ACCESS_COARSE_LOCATION,
            Manifest.permission.ACCESS_FINE_LOCATION,Manifest.permission.WRITE_EXTERNAL_STORAGE,Manifest.permission.READ_PHONE_STATE} ;

    @Override
    protected int getLayoutResource() {
        return R.layout.common_recylerview;
    }

    @Override
    public void initPresenter() {
        mPresenter.setVM(this, mModel);
    }

    @Override
    protected void initView() {
        mHeadBack.setVisibility(View.GONE);
        mRightBtn.setVisibility(View.GONE);
        mHeadTitle.setText("车生活");
        initHeadView();
        initRecyclerView();
        noDataTip.setVisibility(View.GONE);
        mRxManager.on(Constants.RX_EVENT_REFRESH_CAR_LIFE, new Action1<String>() {
            @Override
            public void call(String s) {
                if("loginSuccess".equals(s)) {
                    mPresenter.getLifeNewsList(mPageNum, ApiConstants.PAGE_SIZE_5, true);
                    return ;
                }
                isFirstLoad = true;
            }
        });
    }

    @Override
    public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser && isFirstLoad) {
            Log.i("CarLifeFragment", "coming CarLifeFragment....");
            isFirstLoad = false;
            mPresenter.getLifeNewsList(mPageNum, ApiConstants.PAGE_SIZE_5, true);
        }
    }

    private void initRecyclerView() {
        mRefreshLayout.setOnRefreshListener(this);
        mRefreshLayout.setColorSchemeColors(Constants.RECYCLER_RGB);

        LinearLayoutManager layoutManager = new LinearLayoutManager(getContext());
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);

        mRecyclerView.setLayoutManager(layoutManager);
        mAdapter = new NewsAdapter(null,_mActivity);

        mAdapter.openLoadMore(5, false);
        mAdapter.setOnRecyclerViewItemClickListener(this);
        mRecyclerView.setAdapter(mAdapter);
        mAdapter.addHeaderView(mHeadView);
    }

    private void initHeadView() {
        mHeadView = LayoutInflater.from(getContext()).inflate(R.layout.fg_car_life, null);

        mIllegalInquiriesRl = (RelativeLayout) mHeadView.findViewById(R.id.illegal_inquiries);
        mAnnouncementRl = (RelativeLayout) mHeadView.findViewById(R.id.announcement);
        mChargingStationRl = (RelativeLayout) mHeadView.findViewById(R.id.charging_station);
        mTrafficNavigationRl = (RelativeLayout) mHeadView.findViewById(R.id.traffic_navigation);
        mKckpRl = (RelativeLayout) mHeadView.findViewById(R.id.kckp);

        //no data tip
        noDataTip = (RelativeLayout) mHeadView.findViewById(R.id.no_data_tip);
        //更多
        mCarLifeMore = (TextView) mHeadView.findViewById(R.id.car_life_more);

        noDataTip.setVisibility(View.VISIBLE);

        mIllegalInquiriesRl.setOnClickListener(this);
        mAnnouncementRl.setOnClickListener(this);
        mChargingStationRl.setOnClickListener(this);
        mTrafficNavigationRl.setOnClickListener(this);
        mCarLifeMore.setOnClickListener(this);
        mKckpRl.setOnClickListener(this);
    }

    public static CarLifeFragment newInstance() {
        return new CarLifeFragment();
    }


    @Override
    public void onRefresh() {
        mPageNum = 1;
        noDataTip.setVisibility(View.GONE);
        mAdapter.notifyDataChangedAfterLoadMore(true);
        mPresenter.getLifeNewsList(mPageNum, ApiConstants.PAGE_SIZE_5, false);
    }

    @Override
    public void onClick(View v) {
        if(checkDoubleClick()) {
            switch (v.getId()) {
                case R.id.illegal_inquiries:
                    if(!checkLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, SelectCarFragment.newInstance(SelectCarFragment.FROM_ILLEGAL_INQUIRIES));
                    break;
                case R.id.announcement:
                    if(!checkLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, SelectCarFragment.newInstance(SelectCarFragment.FROM_ANNOUNCEMENT));
                    break;
                case R.id.charging_station:
                    /*if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        *//**
                         * 第 2 步: 请求权限
                         *//*
                        // 一次请求多个权限, 如果其他有权限是已经授予的将会自动忽略掉
                        ActivityCompat.requestPermissions(
                                _mActivity,
                                PERMISSIONS_CONTACT,
                                MY_PERMISSION_REQUEST_CODE
                        );
                    } else {
                        //充电站
                        TrafficMapActivity.gotoTrafficMapActivity(getActivity(), 3);
                    }
*/
                    TrafficMapActivity.gotoTrafficMapActivity(getActivity(), 3);
                    break;
                case R.id.traffic_navigation:
                    //路况导航
                    TrafficMapActivity.gotoTrafficMapActivity(getActivity(), 0);
                    break;
                case R.id.car_life_more:
                    //更多
                    mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, NewsMoreFragment.newInstance());
                    break;
                case R.id.kckp:
                    //快处快赔
                    if(!checkLogin()) {
                        mRxManager.post(Constants.RX_EVENT_NEXT_PAGE, LoginFragment.newInstance());
                        return ;
                    }
                    mPresenter.getKckpUrl();
                    break;
            }
        }
    }

    private boolean checkLogin() {
        return CommonPara.getInstance().isLogin();
    }


    @Override
    public void onItemClick(View view, int i) {
        NewsBean.ListBean bean = mAdapter.getItem(i);
        if(bean != null) {
            RxBus.getInstance().post(Constants.RX_EVENT_NEXT_PAGE, NewDetailFragment.newInstance(bean));
        }
    }

    @Override
    public void requestSuccess(NewsBean info) {
        if (info != null && info.getList() != null && info.getList().size() > 0) {

            mPageCount = Integer.parseInt(info.getTotalnum());
            if (mPageNum == 1) {
                //刷新
                mAdapter.setNewData(info.getList());
            } else {
                //加载更多
                mAdapter.notifyDataChangedAfterLoadMore(info.getList(), true);
            }
        } else {
            //没有搜索到结果
            noDataTip.setVisibility(mPageNum == 1 ? View.VISIBLE : View.GONE);
            mPageNum--;
            mPageCount = mPageNum;
            mAdapter.notifyDataChangedAfterLoadMore(false);
            if (mPageNum > 1) {
                showLongToast("全部加载完毕");
            }
        }
    }

    @Override
    public void onComplete() {
        if (mRefreshLayout.isRefreshing()) {
            mRefreshLayout.setRefreshing(false);
        }
    }

    @Override
    public void getKcKpUrlSuccess(String url) {
        if(!StringUtils.isEmpty(url)) {
            WebViewActivity.gotoWebActivity(getContext(), "快处快赔", url);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == MY_PERMISSION_REQUEST_CODE) {
            boolean isAllGranted = true;

            // 判断是否所有的权限都已经授予了
            for (int grant : grantResults) {
                if (grant != PackageManager.PERMISSION_GRANTED) {
                    isAllGranted = false;
                    break;
                }
            }

            if (isAllGranted) {
                // 如果所有的权限都授予了, 则执行备份代码
                TrafficMapActivity.gotoTrafficMapActivity(getActivity(), 3);
            } else {
                // 弹出对话框告诉用户需要权限的原因, 并引导用户去应用权限管理中手动打开权限按钮
                showErrorTip("拒绝此权限将不能使用此功能");
            }
        }
    }
}
